<template>
    <div class="wxLogin" style="font-size:14px;color:#ccc;">
        {{pageTitle}}
    </div>
</template>

<script>
import { setStore, getStore, GetQueryString } from '@/assets/js/utils.js';
import { appid, globalUrl } from '@/assets/js/const.js';
import { getWxToken, getWxUserinfo,checkOpenIdNew } from '@/api/request.js';
export default {
    name: 'wxLogin',
    data() {
        return {
            pageTitle:'登录中,请稍后...',
            openId:'',
        }
    },
    created() {
       let code = GetQueryString('code');
       if(code){
           console.log('用户code',code)
           this._getWxToken(code);
       }else{
           this.login();
       }
    },
    mounted() {
        this.$store.commit('UPDATE_HEAD', false)
        this.$store.commit('UPDATE_FOOTER', false)
    },
    methods: {
        login(){
            var url = globalUrl+"/wxLogin";
            var testUrl = encodeURIComponent(url);
            var wxcode = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri=" + testUrl + "&response_type=code&scope=snsapi_userinfo&state=wx2013#wechat_redirect";
            location.href = wxcode;
        },
        _getWxToken(code){
            let that = this;
            getWxToken(code).then(res => {
                console.log('code获取的token信息',res.data)
                if (res.code == 1) {
                    let data = JSON.parse(res.data.token);
                    that.openId = data.openid;
                    that._getWxUserinfo(data.access_token,data.openid);
                }
            }).catch(err => console.log(err))
        },
        _getWxUserinfo(token,openid){
            let that = this;
            getWxUserinfo(token,openid).then(res => {
                console.log('用户信息',res.data);
                if (res.code == 1) {
                    let data = JSON.parse(res.data);
                    setStore('user',data);
                    that._checkOpenIdNew(data.openid,data.headimgurl,data.nickname);
                }
            }).catch(err => console.log(err)) 
        },
        //创建用户
        _checkOpenIdNew(openid,avatar,nickName){
            let that = this;
            checkOpenIdNew(openid,avatar,nickName).then(res => {
                console.log('创建用户后',res.data)
                if (res.code == 1) {
                    setStore('userId',res.data.userId);
                    setStore('token',res.data.jwttoken);
                    let fhUrl =  getStore('fhUrl')
                    if(fhUrl){
                        window.location.href = fhUrl
                    }else{
                        that.$router.push('/')
                    }
                }else{
                    that.$Toast('res.msg')
                    that.pageTitle = "网络异常，请稍后再试..."
                }
            }).catch(err => console.log(err)) 
        }
    }
}
</script>
<style scoped lang="scss">
.wxLogin{
    padding: 10px;
}
</style>